<template>
	<view class="container">
		<!-- 顶部标题栏 -->
		<view class="header">
			<text class="header-title">收货地址</text>
			<view class="header-right" @click="addAddress">
				<text class="add-text">添加</text>
			</view>
		</view>
		
		<!-- 地址列表 -->
		<view class="address-list">
			<view 
				class="address-item" 
				v-for="(address, index) in addressList" 
				:key="index"
				@click="selectAddress(address)"
			>
				<view class="address-content">
					<view class="address-header">
						<text class="contact-name">{{ address.name }}</text>
						<text class="contact-phone">{{ address.phone }}</text>
						<view class="default-tag" v-if="address.isDefault == 1">
							<text>默认</text>
						</view>
					</view>
					<text class="address-detail">{{ address.address }}</text>
				</view>
				<view class="address-actions">
					<view class="action-btn edit-btn" @click.stop="editAddress(address, index)">
						<text class="btn-text">编辑</text>
					</view>
					<view class="action-btn delete-btn" @click.stop="deleteAddress(index)">
						<text class="btn-text">删除</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 添加/编辑地址弹窗 -->
		<view class="modal-overlay" v-if="showModal" @click="closeModal">
			<view class="modal-content" @click.stop>
				<view class="modal-header">
					<text class="modal-title">{{ isEdit ? '编辑地址' : '添加地址' }}</text>
					<view class="close-btn" @click="closeModal">
						<text class="close-icon">×</text>
					</view>
				</view>
				
				<view class="form-content">
					<view class="form-item">
						<text class="form-label">收货人</text>
						<input 
							class="form-input" 
							v-model="formData.name" 
							placeholder="请输入收货人姓名"
						/>
					</view>
					
					<view class="form-item">
						<text class="form-label">手机号</text>
						<input 
							class="form-input" 
							v-model="formData.phone" 
							placeholder="请输入手机号"
							type="number"
						/>
					</view>
					
					<view class="form-item">
						<text class="form-label">详细地址</text>
						<textarea 
							class="form-textarea" 
							v-model="formData.address" 
							placeholder="请输入详细地址"
						></textarea>
					</view>
					
					<view class="form-item">
						<view class="checkbox-item" @click="toggleDefault">
							<view class="checkbox" :class="{ checked: formData.isDefault == 1 }">
								<text class="checkmark" v-if="formData.isDefault == 1">✓</text>
							</view>
							<text class="checkbox-label">设为默认地址</text>
						</view>
					</view>
				</view>
				
				<view class="modal-footer">
					<view class="modal-btn cancel-btn" @click="closeModal">
						<text class="btn-text">取消</text>
					</view>
					<view class="modal-btn confirm-btn" @click="saveAddress">
						<text class="btn-text">保存</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			showModal: false,
			isEdit: false,
			editIndex: -1,
			formData: {
				id: '',
				name: '',
				phone: '',
				address: '',
				isDefault: 0
			},
			addressList: [],
			loading: false
		}
	},
	onLoad() {
		// 页面初始化，不在这里加载数据，统一在 onShow 中加载
	},
	onShow() {
		// 页面显示时加载地址列表（包括首次进入和从其他页面返回）
		this.loadAddressList()
	},
	methods: {
		// 加载地址列表
		loadAddressList() {
			this.loading = true
			this.$u.api.address.list().then(res => {
				this.loading = false
				if (res && res.data) {
					this.addressList = res.data.map(item => ({
						id: item.id,
						name: item.receiverName || '',
						phone: item.receiverPhone || '',
						address: item.address || '',
						isDefault: item.isDefault == 1 ? 1 : 0
					}))
				} else {
					this.addressList = []
				}
			}).catch(err => {
				this.loading = false
				console.error('获取地址列表失败:', err)
				uni.showToast({
					title: '获取地址列表失败',
					icon: 'none'
				})
			})
		},
		
		// 返回上一页
		goBack() {
			uni.navigateBack()
		},
		
	// 选择地址
	selectAddress(address) {
		// 将选中的地址传递回上一页
		const pages = getCurrentPages()
		const prevPage = pages[pages.length - 2]
		if (prevPage) {
			prevPage.$vm.deliveryInfo = {
				id: address.id,
				address: address.address,
				name: address.name,
				phone: address.phone
			}
			prevPage.$vm.hasAddress = true
		}
		uni.navigateBack()
	},
		
		// 添加地址
		addAddress() {
			this.isEdit = false
			this.editIndex = -1
			this.resetForm()
			this.showModal = true
		},
		
		// 编辑地址
		editAddress(address, index) {
			this.isEdit = true
			this.editIndex = index
			this.formData = {
				id: address.id,
				name: address.name,
				phone: address.phone,
				address: address.address,
				isDefault: address.isDefault
			}
			this.showModal = true
		},
		
		// 删除地址
		deleteAddress(index) {
			const address = this.addressList[index]
			uni.showModal({
				title: '确认删除',
				content: '确定要删除这个地址吗？',
				success: (res) => {
					if (res.confirm) {
						uni.showLoading({ title: '删除中...' })
						this.$u.api.address.delete({
							id: address.id
						}).then(res => {
							uni.hideLoading()
							if (res && res.result === 'true') {
								this.addressList.splice(index, 1)
								uni.showToast({
									title: '删除成功',
									icon: 'success'
								})
							} else {
								uni.showToast({
									title: res.message || '删除失败',
									icon: 'none'
								})
							}
						}).catch(err => {
							uni.hideLoading()
							console.error('删除地址失败:', err)
							uni.showToast({
								title: '删除失败，请重试',
								icon: 'none'
							})
						})
					}
				}
			})
		},
		
		// 保存地址
		saveAddress() {
			// 验证表单
			if (!this.formData.name) {
				uni.showToast({
					title: '请输入收货人姓名',
					icon: 'none'
				})
				return
			}
			
			if (!this.formData.phone) {
				uni.showToast({
					title: '请输入手机号',
					icon: 'none'
				})
				return
			}
			
			if (!this.formData.address) {
				uni.showToast({
					title: '请输入详细地址',
					icon: 'none'
				})
				return
			}
			
			// 构建保存参数
			const params = {
				receiverName: this.formData.name,
				receiverPhone: this.formData.phone,
				address: this.formData.address,
				isDefault: this.formData.isDefault
			}
			
			// 如果是编辑，添加id
			if (this.isEdit && this.formData.id) {
				params.id = this.formData.id
			}
			
			uni.showLoading({ title: '保存中...' })
			
			this.$u.api.address.save(params).then(res => {
				uni.hideLoading()
				
				if (res && res.result === 'true') {
					uni.showToast({
						title: this.isEdit ? '编辑成功' : '添加成功',
						icon: 'success'
					})
					
					// 重新加载地址列表
					this.loadAddressList()
					this.closeModal()
				} else {
					uni.showToast({
						title: res.message || '保存失败',
						icon: 'none'
					})
				}
			}).catch(err => {
				uni.hideLoading()
				console.error('保存地址失败:', err)
				uni.showToast({
					title: '保存失败，请重试',
					icon: 'none'
				})
			})
		},
		
		// 切换默认地址
		toggleDefault() {
			this.formData.isDefault = this.formData.isDefault == 1 ? 0 : 1
		},
		
		// 关闭弹窗
		closeModal() {
			this.showModal = false
			this.resetForm()
		},
		
		// 重置表单
		resetForm() {
			this.formData = {
				id: '',
				name: '',
				phone: '',
				address: '',
				isDefault: 0
			}
		}
	}
}
</script>

<style scoped>
.container {
	background-color: #fff;
}

/* 顶部标题栏 */
.header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20px;
	background-color: #ffffff;
	border-bottom: 1px solid #f0f0f0;
}

.header-left {
	width: 40px;
	height: 40px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.back-icon {
	font-size: 24px;
	color: #333333;
	font-weight: bold;
}

.header-title {
	font-size: 18px;
	color: #333333;
	font-weight: bold;
}

.header-right {
	padding: 8px 16px;
	background-color: #ff4069;
	border-radius: 20px;
}

.add-text {
	font-size: 14px;
	color: #ffffff;
	font-weight: bold;
}

/* 地址列表 */
.address-list {
	padding: 20px 10px;
}

.address-item {
	background-color: #ffffff;
	border-radius: 12px;
	padding: 20px;
	margin-bottom: 15px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.address-content {
	flex: 1;
	margin-bottom: 15px;
}

.address-header {
	display: flex;
	align-items: center;
	margin-bottom: 8px;
}

.contact-name {
	font-size: 16px;
	color: #333333;
	font-weight: bold;
	margin-right: 15px;
}

.contact-phone {
	font-size: 14px;
	color: #666666;
	margin-right: 15px;
}

.default-tag {
	padding: 2px 8px;
	background-color: #ff4069;
	border-radius: 10px;
}

.default-tag text {
	font-size: 12px;
	color: #ffffff;
}

.address-detail {
	font-size: 14px;
	color: #333333;
	line-height: 1.5;
}

.address-actions {
	display: flex;
    justify-content: center;
	gap: 50px;
}

.action-btn {
	padding: 8px 16px;
	border-radius: 20px;
	border: 1px solid #ddd;
}

.edit-btn {
	border-color: #ff4069;
}

.edit-btn .btn-text {
	color: #ff4069;
}

.delete-btn {
	border-color: #ff6b6b;
}

.delete-btn .btn-text {
	color: #ff6b6b;
}

.btn-text {
	font-size: 14px;
	font-weight: bold;
}

/* 弹窗样式 */
.modal-overlay {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 1000;
}

.modal-content {
	width: 90%;
	max-width: 400px;
	background-color: #ffffff;
	border-radius: 12px;
	overflow: hidden;
}

.modal-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20px;
	border-bottom: 1px solid #f0f0f0;
}

.modal-title {
	font-size: 18px;
	color: #333333;
	font-weight: bold;
}

.close-btn {
	width: 30px;
	height: 30px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.close-icon {
	font-size: 20px;
	color: #999999;
}

.form-content {
	padding: 20px;
}

.form-item {
	margin-bottom: 20px;
}

.form-label {
	font-size: 14px;
	color: #333333;
	margin-bottom: 8px;
	display: block;
}

.form-input {
	width: 90%;
	height: 40px;
	padding: 0 15px;
	border: 1px solid #ddd;
	border-radius: 8px;
	font-size: 14px;
	color: #333333;
}

.form-textarea {
	width: 90%;
	min-height: 80px;
	padding: 15px;
	border: 1px solid #ddd;
	border-radius: 8px;
	font-size: 14px;
	color: #333333;
}

.checkbox-item {
	display: flex;
	align-items: center;
}

.checkbox {
	width: 20px;
	height: 20px;
	border: 2px solid #ddd;
	border-radius: 4px;
	margin-right: 10px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.checkbox.checked {
	border-color: #ff4069;
	background-color: #ff4069;
}

.checkmark {
	font-size: 12px;
	color: #ffffff;
	font-weight: bold;
}

.checkbox-label {
	font-size: 14px;
	color: #333333;
}

.modal-footer {
	display: flex;
	border-top: 1px solid #f0f0f0;
}

.modal-btn {
	flex: 1;
	height: 50px;
	display: flex;
	align-items: center;
	justify-content: center;
}

.cancel-btn {
	border-right: 1px solid #f0f0f0;
}

.cancel-btn .btn-text {
	color: #666666;
}

.confirm-btn {
	background-color: #ff4069;
}

.confirm-btn .btn-text {
	color: #ffffff;
	font-weight: bold;
}
</style>
